package com.littleorange.android.app.net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.littleorange.android.app.utils.Constants;

import android.util.Log;

public class HttpPoster {
	
	private String mUrl = null;
	private HttpPost httpRequest = null;
	
	public HttpPoster(String url){
		this.mUrl = url;
		Log.i(Constants.LittltOrange_LOG, "url : " + this.mUrl);
		this.httpRequest = new HttpPost(url);
	}

	public String post(Map<String, String> data) throws ClientProtocolException, IOException{
		if(data == null || data.isEmpty()){
			return null;
		}
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		
		for(String key : data.keySet()){
			params.add(new BasicNameValuePair(key, data.get(key)));
		}
		
		HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(httpEntity);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = httpClient.execute(httpRequest);
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if(statusCode == HttpStatus.SC_OK){
				return EntityUtils.toString(httpResponse.getEntity());
		}else{
			throw new IOException(String.format("%s status code is %d\n", this.mUrl, statusCode));
		}
	}
	
}
